package com.redis.aopmdx;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

/**
 * 作者: LCG
 * 日期: 2020/7/7 00:32
 * 描述:
 */
@Aspect
@Component
public class TestAspect {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 配置切面
     */
    @Pointcut("execution( public * com.redis.aopmdx.*.*(..) )")
    public void point(){}


    /**
     * 环绕通知可以自由的切入方法
     */
    @Around("point() && @annotation(com.redis.aopmdx.zhujie.MdxAopApi)")
    public Object before(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        //获取请求的上下文
        ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = servletRequestAttributes.getRequest();

        HttpServletResponse response = servletRequestAttributes.getResponse();

        String code = request.getParameter("code");

        if(checkCode(code)){
            return  proceedingJoinPoint.proceed();
        }else{
            response.getOutputStream().print("{aop error}");
            return null;
        }

    }


    /**
     * 检测请求中携带的参数
     * @return
     */
    public boolean checkCode(String code){

        String lua="if redis.call('get',KEYS[1]) then return redis.call('del',KEYS[1]) else return 0 end";

        DefaultRedisScript<Long> defaultRedisScript=new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setScriptText(lua);

        Long execute = redisTemplate.execute(defaultRedisScript, Collections.singletonList(code));

        if(execute==1){
            return true;
        }else{
            return false;
        }

    }

}
